// url: https://leetcode.cn/problems/two-sum/?envType=study-plan-v2&envId=top-interview-150
package interview_classic.hash_table;

import java.util.*;

public class Solution189 {
    // 暴力枚举就不用说了 这个是采用hash表

    public static void main(String[] args) {
        int[] arr = {3,3};
        int target = 6;
        twoSum(arr, target);
    }

    public static int[] twoSum(int[] nums, int target) {
        HashMap<Integer, Set<Integer>> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            Integer num = nums[i];
            if (!map.containsKey(num)) {
                HashSet<Integer> set = new HashSet<>();
                set.add(i);
                map.put(num, set);
            } else {
                map.get(num).add(i);
            }
        }
        int[] ret = new int[2];
        for (int i = 0; i < nums.length; i++) {
            int complement = target - nums[i];
            Set<Integer> set = map.get(complement); // set 是另一半
            if (set != null && (!set.contains(i) || set.size() > 1)) {
                ret[0] = i;
                ret[1] = getNum(set, i);
                return ret;
            }
        }
        return ret;
    }

    private static int getNum(Set<Integer> set, int i) {
        List<Integer> list = set.stream().toList();
        for (Integer num : list) {
            if (num != i) {
                return num;
            }
        }
        return -1;
    }
}
